//
//  APPHomeViewController.swift
//  tree_ai
//
//  Created by yumini on 2024/5/29.
//

import Foundation
import UIKit
import ZLPhotoBrowser
import Alamofire
import ProgressHUD


// 植物花草 botany
// 动物生灵 animal
// 美食文化 food
// 石头矿物 mineral
// 建筑艺术 architecture
// 机械工具 machine


class APPHomeViewController: UIViewController{
    
    let btnCategorys = ["botany", "animal", "food", "mineral", "architecture", "machine"]
    
    override func viewDidLoad() {
        super.viewDidLoad()

        // Do any additional setup after loading the view.
        self.createView()
        
        fetchHostIpv6()
    }
    
    
    func fetchHostIpv6(){
        var url = "https://dynv6.com/api/v2/zones/3986284/records"
    
        var resData: Data? = nil
        //
        let headers: HTTPHeaders = [
            "Authorization": "Bearer KED5zuVyJ6n6D9R2BExD3PMM8okxKM" 
        ]
        

        AF.request(url, method: .get, headers: headers).responseString { result in
            
            //print("type result:\(type(of: result.value) )")
            //print("result:\(result)")
            //print("result.value:\(result.value)")
            
            let resStr = result.value
            
            do {
                resData = resStr!.data(using: .utf8)
                let json = try JSONSerialization.jsonObject(with: resData!, options: [])
                if let dictionary = json as? [String: Any] {
                    // 成功转换为字典
                    print(dictionary)
                } else if let array = json as? [Any] {
                    // 成功转换为数组
                    print(array)
                    let oneRecord = array[0] as? [String: Any]
                    let ipv6 = oneRecord!["data"] as! String
                    print("ipv6:", ipv6)
                    
                    TreeSqlManager.shared.testIpv6Host = ipv6
                } else {
                    print("JSON is not a dictionary or array")
                }
            } catch {
                print("Error parsing JSON: \(error.localizedDescription)")
            }
            
        }
        


        
        
 
        
        //return ipv6
    }
    
    
    
    func createView() {
        self.view.backgroundColor = .white
        
        let imageBtn00 = UIButton()
        imageBtn00.tag = 10000
        self.view.addSubview(imageBtn00)
        imageBtn00.setTitle("植物花草", for: .normal)
        imageBtn00.setTitleColor(.white, for: .normal)
        imageBtn00.backgroundColor = .cyan
        imageBtn00.snp.makeConstraints { make in
            make.top.equalTo(self.view.safeAreaLayoutGuide.snp.top)
            make.left.equalTo(6)
            //make.width.equalTo(100)
            make.right.equalToSuperview { sv in
                sv.snp_centerXWithinMargins
            }.offset(-3)
            make.height.equalTo(100)
        }
        imageBtn00.addTarget(self, action: #selector(buttonTapped(btn:)), for: .touchUpInside)
        
        
        self.view.backgroundColor = .white
        
        let imageBtn01 = UIButton()
        imageBtn01.tag = 10001
        self.view.addSubview(imageBtn01)
        imageBtn01.setTitle("动物生灵", for: .normal)
        imageBtn01.setTitleColor(.white, for: .normal)
        imageBtn01.backgroundColor = .cyan
        imageBtn01.snp.makeConstraints { make in
            make.top.equalTo(imageBtn00.snp.top)
            make.right.equalTo(-6)
            //make.width.equalTo(100)
            make.left.equalToSuperview { sv in
                sv.snp_centerXWithinMargins
            }.offset(3)
            make.height.equalTo(100)
        }
        imageBtn01.addTarget(self, action: #selector(buttonTapped(btn:)), for: .touchUpInside)
        
        
        let imageBtn10 = UIButton()
        imageBtn10.tag = 10002
        self.view.addSubview(imageBtn10)
        imageBtn10.setTitle("美食文化", for: .normal)
        imageBtn10.setTitleColor(.white, for: .normal)
        imageBtn10.backgroundColor = .cyan
        imageBtn10.snp.makeConstraints { make in
            make.top.equalTo(imageBtn00.snp.bottom).offset(6)
            make.left.equalTo(6)
            //make.width.equalTo(100)
            make.right.equalToSuperview { sv in
                sv.snp_centerXWithinMargins
            }.offset(-3)
            make.height.equalTo(100)
        }
        imageBtn10.addTarget(self, action: #selector(buttonTapped(btn:)), for: .touchUpInside)
        
        
        self.view.backgroundColor = .white
        
        let imageBtn11 = UIButton()
        imageBtn11.tag = 10003
        self.view.addSubview(imageBtn11)
        imageBtn11.setTitle("石头矿物", for: .normal)
        imageBtn11.setTitleColor(.white, for: .normal)
        imageBtn11.backgroundColor = .cyan
        imageBtn11.snp.makeConstraints { make in
            make.top.equalTo(imageBtn10.snp.top)
            make.right.equalTo(-6)
            //make.width.equalTo(100)
            make.left.equalToSuperview { sv in
                sv.snp_centerXWithinMargins
            }.offset(3)
            make.height.equalTo(100)
        }
        imageBtn11.addTarget(self, action: #selector(buttonTapped(btn:)), for: .touchUpInside)
        
        
        
        
        let imageBtn20 = UIButton()
        imageBtn20.tag = 10004
        self.view.addSubview(imageBtn20)
        imageBtn20.setTitle("建筑艺术", for: .normal)
        imageBtn20.setTitleColor(.white, for: .normal)
        imageBtn20.backgroundColor = .cyan
        imageBtn20.snp.makeConstraints { make in
            make.top.equalTo(imageBtn10.snp.bottom).offset(6)
            make.left.equalTo(6)
            //make.width.equalTo(100)
            make.right.equalToSuperview { sv in
                sv.snp_centerXWithinMargins
            }.offset(-3)
            make.height.equalTo(100)
        }
        imageBtn20.addTarget(self, action: #selector(buttonTapped(btn:)), for: .touchUpInside)
        
        
        self.view.backgroundColor = .white
        
        let imageBtn21 = UIButton()
        imageBtn21.tag = 10005
        self.view.addSubview(imageBtn21)
        imageBtn21.setTitle("机械工具", for: .normal)
        imageBtn21.setTitleColor(.white, for: .normal)
        imageBtn21.backgroundColor = .cyan
        imageBtn21.snp.makeConstraints { make in
            make.top.equalTo(imageBtn20.snp.top)
            make.right.equalTo(-6)
            //make.width.equalTo(100)
            make.left.equalToSuperview { sv in
                sv.snp_centerXWithinMargins
            }.offset(3)
            make.height.equalTo(100)
        }
        imageBtn21.addTarget(self, action: #selector(buttonTapped(btn:)), for: .touchUpInside)
        
    }
    
    
    @objc func buttonTapped(btn: UIButton) {
        // 这里是按钮点击后的处理逻辑
        print("Button was tapped")
        //let findInfoVc = FindInfoViewController.init()
        //self.navigationController?.pushViewController(findInfoVc, animated: true)
        
        let cateIndex = btn.tag - 10000
        var cate = btnCategorys[cateIndex]//"botany"
        
        let config = ZLPhotoConfiguration.default()
        config.maxSelectCount = 1
        config.allowEditImage = false
        config.allowSelectVideo = false
        config.allowSelectOriginal = false
        config.allowTakePhotoInLibrary = true
    
        
        let ps = ZLPhotoPreviewSheet()
        
        ps.selectImageBlock = { [weak self] results, isOriginal in
            // your code
            print("select: \(results)  isOriginal:\(isOriginal)")
            if (results.count > 0) {
                let imgModel = results[0]
                
                self?.uploadImage(img: imgModel.image, category:cate)
            }
        }
        //ps.showPhotoLibrary(sender: self)
        
        ps.showPreview(sender: self)
        
    }
    
    func uploadImage(img: UIImage, category: String) {
        ProgressHUD.showProgress(0)
        
        let imgSize = img.size
        print("imgSize: \(imgSize)")
        
        let uuid = TreeSqlManager.shared.snowFlake.nextID()
        let fileName = String(format: "%@_%llu.jpg", category,uuid!)
        
        let imgData = img.jpegData(compressionQuality: 0.85)
        
        let uploadURL = "https://chatglm.cn/chatglm/backend-api/assistant/file_upload"
        
        var request = URLRequest(url: URL(string: uploadURL)!)
        request.httpMethod = "POST"
        
        
        AF.upload(multipartFormData: { multipartFormData in
            multipartFormData.append(imgData!, withName: "file", fileName: fileName) //, mimeType: "jpg"
        }, with: request).uploadProgress(closure: { progress in
            print("progress:\(progress)")
            ProgressHUD.showProgress(progress.fractionCompleted)
        })
        .responseJSON { response in
            switch response.result {
                case .success:
                    print("Upload finish")
                    if let json = response.value {
                        print("JSON type:\(type(of:json)): \(json)")
                        let jsonDict = json as? Dictionary<String, Any>
                        let resultDict = jsonDict?["result"] as? Dictionary<String, Any>
                        if resultDict != nil {
                            let file_id = resultDict?["file_id"] as? String
                            let file_name = resultDict?["file_name"] as? String
                            let file_url = resultDict?["file_url"] as? String
                            let file_size = resultDict?["file_size"] as! Int64
                            
                            let rowId = TreeSqlManager.shared.insertTree(category: category,image_name: file_name!, image_url: file_url!, image_id: file_id!, image_file_size: file_size)
                            //self.reloadFromDataBase()
                            
                            let findInfoVc = FindInfoViewController.init()
                            findInfoVc.localTreeId = rowId
                            self.navigationController?.pushViewController(findInfoVc, animated: true)
                            
                        }
                        
                    }
                    //ProgressHUD.succeed("上传成功！")
                    ProgressHUD.showSucceed("上传成功！", interaction: false, delay: 1.0)
                case .failure(let error):
                    print("Upload failed: \(error.localizedDescription)")
            }
        }
    }
    
}
